package cn.kgc.listener;

import cn.kgc.base.dto.LockStockDTO;
import cn.kgc.base.vo.OrderVo;
import cn.kgc.client.OmsFeignClient;
import cn.kgc.commons.exception.HttpException;
import cn.kgc.commons.vo.Result;
import cn.kgc.constant.OrderStatusEnum;
import cn.kgc.service.WmsWareSkuService;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.List;

/**
 * <p></p>
 *
 * @author 李孟鸠
 * @Date: 2023年01月05日12:01
 */
@Component
@Slf4j
public class WmsWareSkuListener {

    @Resource
    private OmsFeignClient omsFeignClient;

    @Resource
    private WmsWareSkuService wmsWareSkuService;

    @RabbitListener(queues = "stock.unlock.queue")
    public void receiveUnlockStockMessage(List<LockStockDTO>lockStockDTOList,

                                          Channel channel, Message message) {
        long tag = message.getMessageProperties().getDeliveryTag();
        log.info("接收到消息:{}", message);
        //释放库存,获得释放订单的库存的编号
        String orderSn = lockStockDTOList.get(0).getOrderSn();
        try {


            // 根据订单的编号获得订单的状态,如果订单的状态是已经关闭，释放库存
            Result<OrderVo> result = omsFeignClient.getOrderVo(orderSn);

            //1 服务降级，没有拿到订单数据，重新获得订单的数据，抛出异常信息
            if(result.getMessage().equals("error")){
                throw new HttpException(50003,
                        HttpStatus.INTERNAL_SERVER_ERROR.value());
            }
            //2 服务没有降级，拿到订单数据，但是我们根据订单编号获得订单为null,此时
            // 需要解锁库存
            if (result.getData()==null){
                wmsWareSkuService.unlockStock(lockStockDTOList);
            }
            //3 服务没有降级，拿到订单数据，订单不为null,订单的状态是已经关闭，解锁库存
            OrderVo orderVo=result.getData();
            if(orderVo.getStatus()== OrderStatusEnum.CLOSED.getOrderStatus()){
                //订单已经关闭，释放库存
                wmsWareSkuService.unlockStock(lockStockDTOList);

            }
            channel.basicAck(tag,false);


        } catch (IOException e) {
            log.error("释放库存失败:{}",orderSn);
            try {
                channel.basicNack(tag,false,true);
            } catch (IOException e1) {
                log.error("处理失败的信息回到消息队列的操作失败：{}",orderSn);
            }
        }


    }
}
